package com.ygqh.baby.handler;

import com.ygqh.baby.ao.AppType;
import com.ygqh.baby.constant.Constant;
import com.ygqh.baby.constant.RedisConstant;
import com.ygqh.baby.model.YgLoginModel;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.YgUserService;
import com.ygqh.baby.service.impl.DocumentConstant;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * @Author: sunshuo
 * @Date: 2019/5/5 10:53
 * @Version: 1.0
 */
@Component
public class LoginHandler {

	@Autowired
	private DocumentConstant documentConstant;
	@Autowired
	private YgUserService ygUserService;
	@Autowired
	private RedisDao redisDao;

	/**
	 * 静默登录
	 * @param user
	 * @param appType
	 * @return
	 */
	public YgLoginModel loginSilent(YgUser user, AppType appType) {
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());
		YgLoginModel model;
		try {
			subject.login(token);
			if(subject.isAuthenticated()) {
				user  = (YgUser) subject.getPrincipal();
			}
			model = new YgLoginModel("LOGIN_SUCCESS", documentConstant.LOGIN_SUCCESS);
			model.setSessionId(subject.getSession().getId());
			user.setIsNewCustomer(ygUserService.isNewCustom(user.getId(), Constant.YIJIADIAN_PLATFORM_NO));
			user.setPassword(null);
			user.setSalt(null);
			model.setUser(user);
			this.resetAppToken(user.getId().toString(), appType, model.getSessionId());
		} catch (UnknownAccountException e) {
			model = new YgLoginModel("UNKNOWN_ACCOUNT", documentConstant.UNKNOWN_ACCOUNT);
		} catch (IncorrectCredentialsException e) {
			model = new YgLoginModel("INCORRECTCREDENTIALS", documentConstant.INCORRECTCREDENTIALS);
		} catch (Exception e) {
			e.printStackTrace();
			model = new YgLoginModel("UNKNOWN_ERROR", documentConstant.UNKNOWN_ERROR);
		}
		return model;
	}

	/**
	 * 缓存App登录的Token （即JSESSIONID）用于消息推送（alias）
	 *
	 * @param userId
	 * @param token  入参
	 * @return void    返回类型
	 * @throws
	 * @Title: resetAppToken
	 * @author （guohao）
	 * @date 2018年4月16日 上午11:35:55
	 * @version V1.0
	 */
	public void resetAppToken(String userId, AppType appType, Serializable token) {
		String appTokenKey = this.getAppTokenKey(userId, appType);
		if (token == null) {
			redisDao.del(appTokenKey.getBytes());
		} else {
			redisDao.set(appTokenKey, token.toString(), 0);
		}

	}

	private String getAppTokenKey(String userId, AppType appType) {
		return String.format(RedisConstant.APP_TOKEN_KEY_PREFIX, appType.name(), userId);
	}

}
